<template>
    <div>
        <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
            <el-menu-item>
                <img style="width: 100px" src="@/assets/NERV.png" alt="Element logo" />
            </el-menu-item>

            <el-menu-item index="1" @click="navigateTo('/')">首页</el-menu-item>
            <el-menu-item index="2" @click="navigateTo('/cart')">购物车</el-menu-item>
            <el-menu-item index="3" @click="navigateTo('/order')">订单</el-menu-item>
            <el-menu-item index="4" @click="navigateTo('/detail')">关于</el-menu-item>

            <div class="flex-grow"></div>

            <el-menu-item index="5">{{ name }},欢迎你</el-menu-item>
            <el-menu-item index="6" v-if="name == '游客'"><router-link to="/login">登录/注册</router-link></el-menu-item>
            <el-menu-item index="7" v-else @click="goBack">退出</el-menu-item>
        </el-menu>
    </div>
</template>

<script>
import router from "@/router";

export default {
    data() {
        return {
            name: '游客', // 用户名，默认“游客”
            activeIndex: "1", // 默认选中菜单项
        };
    },

    mounted() {

        if (sessionStorage.getItem('username') == null) {
            this.name = '游客'
        } else {
            this.name = sessionStorage.getItem('username')
        }
        this.updateActiveIndex();
        console.log(this.name);
    },
    methods: {
        goBack() {
            this.name = '游客',
            sessionStorage.setItem('username', '游客')
        },

        // 更新菜单选中状态
        updateActiveIndex() {
            const routeMap = {

                "/cart": "2",
                "/order": "3",
                "/detail": "4",

            };
            this.activeIndex = routeMap[this.$route.path] || "1"; // 未匹配时默认首页
        },


        // 菜单项点击事件
        // handleSelect(index) {
        //     // this.activeIndex = index; // 更新选中项
        // },
        navigateTo(path) {
            router.push(path);
        },
    },
    // watch: {
    //     // 监听路由变化并更新选中项
    //     $route() {
    //         this.updateActiveIndex();
    //     },
    // },
};
</script>


<style>
a:-webkit-any-link {
    text-decoration: none;
}

.flex-grow {
    flex-grow: 1;
}
</style>